<template>
	<view class="page">
		<cu-custom bgColor="bg-white" :isBack="true"><block slot="content"></block></cu-custom>
		<canvas canvas-id="myCanvas" :style="canvasStyle"></canvas>
		<view class='whiteContent'>
		  <image v-if="tempSavedImageURL" :src='tempSavedImageURL' mode='aspectFit' style='height:100%;width:100%' @longpress="longpressPoster"></image>
		</view>
		<view class='margin-top-sm bg-white flex-1' style="position: fixed;bottom:0;width: 100%;">
			<view class='bg-white flex align-center justify-center padding' style="width: 100%;" v-if="izShare" @tap='share()'>
				<view class="cuIcon-share text-xl text-fw600 text-333"></view>
				<view class="text-333 text-fw600">选择海报 长按分享</view>
			</view>
			<view class='bg-white flex align-center justify-center padding' style="width: 100%;" v-else @tap='saveImage_try'>
				<view class="cuIcon-down text-xl text-fw600 margin-right-sm text-333"></view>
				<view class="text-333 text-fw600">保存至手机</view>
			</view>
		</view> 
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// bgImageUrl: 'https://upload.chinalianjiu.com/productImagesother/C8CA9191D3BB4B1D8A6A592E59FE6FBB.png',
				bgImageUrl: uni.getStorageSync('sharePoster').share_image,
				qrCodeUrl: uni.getStorageSync('sharePoster').miniQrcode,	
				imagePath_bg: undefined,       //wx.getImageInfo转化的图片地址；cavas不能直接用网络地址。
				imagePath_qrcode: undefined,    ////wx.getImageInfo转化的图片地址 ;网络动态请求，小程序码网络图片
				tempSavedImageURL: '',  //cavas绘制图片临时保存路径
				//注意，背景图片时固定大小600x1067，所以canvasStyle宽高比例必须也一致！否则画出来的图片会有多余的一片空白。
				canvasStyle: 'width: 600px;height:1067px;position: fixed;top: -10000px;', 
				izShare:false
			};
		},
		onLoad: function (options) {
		    this.ctx = wx.createCanvasContext('myCanvas', this);
		//创建ctx耗时较长，延时500毫秒再请求url
		    setTimeout(res => {
		      this.requestMyIQRCodeUrl()
		    }, 500)
		 },
		 onBackPress() {
		 	uni.removeStorageSync('sharePoster')
		 },
		 beforeDestroy() {
		 	uni.removeStorageSync('sharePoster')
		 },
		methods:{
			goBackPage: function() {
				uni.navigateBack({
					delta:-1
				})
			},
			requestMyIQRCodeUrl: function() {
			    let that = this
			    // this.qrCodeUrl = uni.getStorageSync('sharePoster').miniQrcode;
				
			    that.draw_try()
			},
			draw_try: function (e) {
			    let urlStr = this.qrCodeUrl;
				// let urlStr = 'http://lianjiu.oss-cn-hangzhou.aliyuncs.com/productImagesnormal/B0943FEB53CB4717B7C7CEAB4113AC6C.png'
				// console.log(urlStr)
			    if (urlStr == '' || urlStr == undefined) {
			      return;
			    }
				uni.showToast({
					icon:'loading',
					title:'加载中'
				})
			    let that = this;
				// 小程序码图片
				wx.getImageInfo({
				  src: urlStr,
				  success: function (sres) {
				    that.imagePath_qrcode = sres.path;
				    that.drawCanvasCxt_try()
				  },
				  fail: function (err) {
					  // console.log('getQRcodeImageInfo',err)
					  uni.showToast({
					  	icon:'none',
					  	title:'加载失败'
					  })
					  that.goBackPage()
				  },
				})
			    // 背景图片
			    wx.getImageInfo({
			      src: that.bgImageUrl,
			      success: function (sres) {
					  // console.log(sres)
			        that.imagePath_bg = sres.path;
			        that.drawCanvasCxt_try()
			      },
			      fail: function (err) {
					  // console.log('getBGImageInfo',err)
					  uni.showToast({
					  	icon:'none',
					  	title:'加载失败'
					  })
					  that.goBackPage()
			      },
			    })
			    
			  },
			  drawCanvasCxt_try: function () {
			 //异步调2次此方法；需获取到2张图片特殊路径canvas才能开始绘图
			    if (this.imagePath_bg != undefined && this.imagePath_qrcode != undefined) {
					uni.showToast({
						icon:'loading',
						title:'海报生成中',
						duration:4000
					})
					this.drawCanvasCxt(this.imagePath_bg, this.imagePath_qrcode)
			    }
			  },
			drawCanvasCxt: function (imagePath_bg, imagePath_qrcode) {
				const res = wx.getSystemInfoSync();
			    const platform = res.platform;
			    let time = 0;
			    if (platform === 'android') {
			      // 在安卓平台，经测试发现如果海报过于复杂在转换时需要做延时，要不然样式会错乱
			      time = 300;
			    }
				//绘制背景图片，大小跟cavas一致。单位是px。如果是本地图片，不要搞太高清，毕竟小程序限制打包后<2M。
			    this.ctx.drawImage(imagePath_bg, 0, 0, 600, 1067)
				//算出小程序码相对于背景海报的坐标。可以写个大概再根据效果慢慢调整
			    // this.ctx.drawImage(imagePath_qrcode, 250, 1067-180, 100, 100)
				this.ctx.drawImage(imagePath_qrcode, 450, 1067-155, 110, 110)
			    let that = this;
				//开始渲染
			    this.ctx.draw(false, () => {
					setTimeout(() => {
						wx.canvasToTempFilePath({
							canvasId: 'myCanvas',
							success: function (res) {
								let url = res.tempFilePath 
								console.log('url=' + url)
								that.tempSavedImageURL = url    // 返回的图片地址保存到一个全局变量里
								uni.hideToast()
							}
						});
					}, time);
			    });
			},  
			saveImage_try: function () {
			    let urlStr = this.tempSavedImageURL;
			    if (urlStr == '' || urlStr == undefined) {
			        return;
			    }
			    let that = this;
			    wx.getSetting({
			      success(res) {
			        if (!res.authSetting['scope.writePhotosAlbum']) {
			          wx.authorize({
			            scope: 'scope.writePhotosAlbum',
			            success() {
			              that.saveImage_do();
			            },
			            fail(err) {
			              
			            }
			          })
			        }else {
			          that.saveImage_do();
			        }
			      }
			    }) 
			},
			saveImage_do: function (e) {
				let that = this
				let urlStr = this.tempSavedImageURL;
				if (urlStr == '' || urlStr == undefined) {
					return
				}
				wx.saveImageToPhotosAlbum({
					filePath: urlStr,
					success: function (fres) {
						console.log('fres',fres,urlStr)
						uni.showToast({
							icon:'none',
							title: '保存成功'
						})
						that.izShare = true
					},
					fail: function (err) {
						uni.showToast({
							icon:'none',
							title: '保存失败'									
						});			   
					},
				})
			},  
			share(){
				uni.chooseImage({
				    count: 1,
				    sizeType: ['original', 'compressed'],
				    sourceType: ['album'],
				    success: function(res) {
						// console.log(chooseImage)
				        // 预览图片
				        uni.previewImage({
				            urls: res.tempFilePaths,
				            longPressActions: {
				                itemList: ['发送给朋友', '收藏'],
				                success: function(data) {
				                    console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				                },
				                fail: function(err) {
				                    console.log(err.errMsg);
				                }
				            }
				        })
				    }
				})
			},
			longpressPoster(){
				console.log('longpressPoster')
				let imgUrl = this.tempSavedImageURL
				uni.previewImage({
				    urls: imgUrl,
				    longPressActions: {
				        itemList: ['发送给朋友', '保存图片', '收藏'],
				        success: function(data) {
				            console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				        },
				        fail: function(err) {
				            console.log(err.errMsg);
				        }
				    }        
				});
			}   
		}
	}
</script>

<style lang="scss">
.whiteContent{
	width: 80%;
	height: 80%;
	margin: 0 auto;
}
</style>
